package com.tech.koufu.ui.activity.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.Volley;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R; 
import com.tech.koufu.model.CompetitionGroup;
import com.tech.koufu.model.TrackerUser;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.ExpertsActivity;
import com.tech.koufu.ui.activity.UserDetailActivity;
import com.tech.koufu.ui.adapter.TrackAdapter;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 
 * @ClassName: MyTrackActivity
 * @Description: 菜单->我的跟踪  
 * @author jl_luo
 * @date 2015年4月4日 上午10:52:58
 */
public class MyTrackActivity extends Activity implements OnClickListener{

	private int page = 1;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView;
	private TrackAdapter mAdapter;
	
	private ArrayList<TrackerUser> datas;
	
	private RequestQueue mQueue; 
	private MyApplication myApp;
	CookieStringRequest stringRequest;
	BitmapUtils bitmapUtils;
	private String userid;
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu_my_track); 
		myApp = (MyApplication) getApplication();
		initView(); 
		initData();
	}
	@Override
	protected void onResume() { 
		super.onResume();
	}
	private void initView() { 
		userid = getIntent().getStringExtra("userid");
		findViewById(R.id.img_callback).setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.tv_title); 
		if(userid!=null && myApp.getUserid().equals(userid)){
			title.setText(R.string.menu_myTrack);
		}else{
			title.setText(R.string.txt_track);
		}
		
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.lv_pull);
		actualListView = mPullToRefreshListView.getRefreshableView(); 
        registerForContextMenu(actualListView);
        bitmapUtils =  new BitmapUtils(this);
        mAdapter = new TrackAdapter(getApplicationContext(),bitmapUtils);
		actualListView.setAdapter(mAdapter);
		actualListView.setOnItemClickListener(itemClick);
	}
	private void initData(){ 
		datas = new ArrayList<TrackerUser>();
		mQueue = Volley.newRequestQueue(getApplicationContext());  
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	datas.clear();
		        	page=1; 
		        }else {
		        	page++; 
		        }  
				load();
			}
		});
		mPullToRefreshListView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, false, true));
		mPullToRefreshListView.setRefreshing(true);
		mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
		mAdapter.mQueue = mQueue;
		mAdapter.sessionID = myApp.phpsessid;
	}
	private void load(){
		String url = Statics.URL_PHP+Statics.IF_MYTRACK; 
		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {   
				if(!TextUtils.isEmpty(response)){
					try { 
						Log.d("tracker", response);
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						if(status.equals("0")){
							JSONArray arry = obj.optJSONArray("data");
							if(arry!=null){
								int length = arry.length();
								for(int i=0;i<length;i++){
									JSONObject o = arry.getJSONObject(i);
									TrackerUser cg = new TrackerUser(o);
									datas.add(cg);
								}
								if(null!=datas && datas.size()>0){
									mAdapter.datas = datas;
									mAdapter.notifyDataSetChanged(); 
								}  
							}else{
								page--;
							}
						}else{  
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				}
				mPullToRefreshListView.onRefreshComplete();
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("page", page+"");    
				params.put("userID", myApp.getUserid());
				return params;
			}
		}; 
		stringRequest.setHeader(myApp.phpsessid);
		mQueue.add(stringRequest);
	}
	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) { 
//			Toast.makeText(getApplicationContext(), position+","+id, Toast.LENGTH_SHORT).show();
			TrackerUser tu = datas.get(position-1);
			Intent intent = new Intent(MyTrackActivity.this,UserDetailActivity.class);
			intent.putExtra("userid", tu.trackId);
			intent.putExtra("username", tu.trackName);
			startActivity(intent);
		}
	};
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_callback:
			this.finish();
			break;
		case R.id.btn_refresh:
			load();
			break;

		default:
			break;
		}
		
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
